clear all
set more off , perm
capture log close

********************************************************************************
** This file creates a panel with info on whether a petrol station is treated **
********************************************************************************		
	
****************************************************
** Create data set with polygons that are treated **
****************************************************

// Create reports data set
use radio_stations_daily_panel.dta, clear
keep if petrol_reports == "yes"
gen pepe = 1
collapse (mean) pepe , by(parent_id id name)
drop pepe
save reports.dta , replace



****************************************************
** Create data set with polygons that are treated **
****************************************************

//	Create polygons from shapefile
shp2dta using "$raw/08_Germany_radio/radio_transmitters_FM_mmqis_node.shp", data("$dta/radio_transmitters_data") coordinates("$dta/radio_transmitters_coord.dta") replace


//	Create file with transmitter information
cd "$dta"
use radio_transmitters_data.dta, clear

split uniq_id, parse(_) generate(id)
destring id1, gen(id)
keep _ID id 

save  radio_transmitters_data_id.dta, replace



************************************
** Merge stations to transmitters **
************************************

cd "$dta"
use stations.dta, clear 

keep id_data latitude longitude

geoinpoly latitude longitude using radio_transmitters_coord.dta

merge m:1 _ID using radio_transmitters_data_id, keep(match master)
drop _merge

bysort id_data id: gen pepe = _n
keep if pepe == 1
drop pepe

sort id_data
save petrol_coord_treatment_contours_radiostations.dta, replace


*******************************
** Identify treated stations **
*******************************

// Open data
cd "$dta"
use petrol_coord_treatment_contours_radiostations.dta , clear

// Only keep treated stations
merge m:1 id using reports.dta
keep if _merge == 3
drop _merge name latitude longitude parent_id

// There might be petrol stations that are reached by several transmitters of one radio station. Want them only once.
collapse _ID , by(id_data id)
rename id radio_station_id
drop _ID

gen treated_ = "yes"
reshape wide treated_ , i(id_data) j(radio_station_id)

cd "$dta"
save treated_petrol_stations.dta , replace



* Erase intermediate data 
erase petrol_coord_treatment_contours_radiostations.dta 
erase radio_stations_daily_panel.dta 
erase radio_transmitters.dta 
erase radio_transmitters_coord.dta 
erase radio_transmitters_data.dta 
erase radio_transmitters_data_id.dta 
erase reports.dta 

